import React, { useState } from 'react';
import {
  Layout,
  Menu,
  Avatar,
  Dropdown,
  Badge,
  Space,
  Button,
  Typography,
  Breadcrumb,
  theme
} from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DashboardOutlined,
  UserOutlined,
  ShoppingOutlined,
  FundOutlined,
  BarChartOutlined,
  SettingOutlined,
  MonitorOutlined,
  SecurityScanOutlined,
  BellOutlined,
  LogoutOutlined,
  ProfileOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import type { MenuProps } from 'antd';

const { Header, Sider, Content, Footer } = Layout;
const { Text } = Typography;

interface AdminLayoutProps {
  children?: React.ReactNode;
}

const AdminLayout: React.FC<AdminLayoutProps> = () => {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();
  const { token } = theme.useToken();
  
  // 从Redux获取用户信息
  const user = useSelector((state: any) => state.auth.user);
  const notifications = useSelector((state: any) => state.ui.notifications);

  // 菜单项配置
  const menuItems: MenuProps['items'] = [
    {
      key: '/admin/dashboard',
      icon: <DashboardOutlined />,
      label: '仪表盘',
    },
    {
      key: '/admin/users',
      icon: <UserOutlined />,
      label: '用户管理',
      children: [
        {
          key: '/admin/users/list',
          label: '用户列表',
        },
        {
          key: '/admin/users/roles',
          label: '角色管理',
        },
        {
          key: '/admin/users/permissions',
          label: '权限配置',
        },
      ],
    },
    {
      key: '/admin/products',
      icon: <ShoppingOutlined />,
      label: '产品管理',
      children: [
        {
          key: '/admin/products/list',
          label: '产品列表',
        },
        {
          key: '/admin/products/categories',
          label: '产品分类',
        },
        {
          key: '/admin/products/risk-rating',
          label: '风险评级',
        },
        {
          key: '/admin/products/audit',
          label: '产品审核',
        },
      ],
    },
    {
      key: '/admin/investments',
      icon: <FundOutlined />,
      label: '投资管理',
      children: [
        {
          key: '/admin/investments/portfolios',
          label: '投资组合',
        },
        {
          key: '/admin/investments/allocation',
          label: '资产配置',
        },
        {
          key: '/admin/investments/stop-loss',
          label: '止损策略',
        },
        {
          key: '/admin/investments/transactions',
          label: '交易记录',
        },
      ],
    },
    {
      key: '/admin/analytics',
      icon: <BarChartOutlined />,
      label: '数据分析',
      children: [
        {
          key: '/admin/analytics/users',
          label: '用户分析',
        },
        {
          key: '/admin/analytics/products',
          label: '产品分析',
        },
        {
          key: '/admin/analytics/returns',
          label: '收益分析',
        },
        {
          key: '/admin/analytics/risks',
          label: '风险分析',
        },
      ],
    },
    {
      key: '/admin/system',
      icon: <SettingOutlined />,
      label: '系统管理',
      children: [
        {
          key: '/admin/system/config',
          label: '系统配置',
        },
        {
          key: '/admin/system/parameters',
          label: '参数设置',
        },
        {
          key: '/admin/system/dictionary',
          label: '数据字典',
        },
        {
          key: '/admin/system/api',
          label: '接口管理',
        },
      ],
    },
    {
      key: '/admin/monitoring',
      icon: <MonitorOutlined />,
      label: '监控中心',
      children: [
        {
          key: '/admin/monitoring/system',
          label: '系统监控',
        },
        {
          key: '/admin/monitoring/performance',
          label: '性能监控',
        },
        {
          key: '/admin/monitoring/exceptions',
          label: '异常监控',
        },
        {
          key: '/admin/monitoring/logs',
          label: '日志管理',
        },
      ],
    },
    {
      key: '/admin/security',
      icon: <SecurityScanOutlined />,
      label: '安全中心',
      children: [
        {
          key: '/admin/security/audit-logs',
          label: '审计日志',
        },
        {
          key: '/admin/security/login-records',
          label: '登录记录',
        },
        {
          key: '/admin/security/operation-records',
          label: '操作记录',
        },
        {
          key: '/admin/security/settings',
          label: '安全设置',
        },
      ],
    },
  ];

  // 用户下拉菜单
  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <ProfileOutlined />,
      label: '个人资料',
      onClick: () => navigate('/admin/profile'),
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '账户设置',
      onClick: () => navigate('/admin/settings'),
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
    },
  ];

  // 处理菜单点击
  const handleMenuClick = ({ key }: { key: string }) => {
    navigate(key);
  };

  // 处理退出登录
  function handleLogout() {
    // 清除认证信息
    dispatch({ type: 'auth/logout' });
    navigate('/login');
  }

  // 生成面包屑
  const generateBreadcrumb = () => {
    const pathSnippets = location.pathname.split('/').filter(i => i);
    const breadcrumbItems = pathSnippets.map((snippet, index) => {
      const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
      const isLast = index === pathSnippets.length - 1;
      
      // 根据路径生成面包屑名称
      const getBreadcrumbName = (path: string) => {
        const nameMap: Record<string, string> = {
          admin: '管理后台',
          dashboard: '仪表盘',
          users: '用户管理',
          products: '产品管理',
          investments: '投资管理',
          analytics: '数据分析',
          system: '系统管理',
          monitoring: '监控中心',
          security: '安全中心',
          list: '列表',
          roles: '角色管理',
          permissions: '权限配置',
        };
        return nameMap[path] || path;
      };

      return {
        title: getBreadcrumbName(snippet),
        href: isLast ? undefined : url,
      };
    });

    return breadcrumbItems;
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      {/* 侧边栏 */}
      <Sider 
        trigger={null} 
        collapsible 
        collapsed={collapsed}
        width={256}
        style={{
          background: token.colorBgContainer,
          borderRight: `1px solid ${token.colorBorderSecondary}`,
        }}
      >
        {/* Logo区域 */}
        <div 
          style={{
            height: 64,
            display: 'flex',
            alignItems: 'center',
            justifyContent: collapsed ? 'center' : 'flex-start',
            padding: collapsed ? 0 : '0 24px',
            borderBottom: `1px solid ${token.colorBorderSecondary}`,
          }}
        >
          {!collapsed && (
            <>
              <img 
                src="/logo.svg" 
                alt="Logo" 
                style={{ width: 32, height: 32, marginRight: 12 }}
              />
              <Text strong style={{ fontSize: 16, color: token.colorPrimary }}>
                测试DEMO后台
              </Text>
            </>
          )}
          {collapsed && (
            <img 
              src="/logo.svg" 
              alt="Logo" 
              style={{ width: 32, height: 32 }}
            />
          )}
        </div>

        {/* 导航菜单 */}
        <Menu
          mode="inline"
          selectedKeys={[location.pathname]}
          openKeys={collapsed ? [] : undefined}
          items={menuItems}
          onClick={handleMenuClick}
          style={{
            border: 'none',
            height: 'calc(100vh - 64px)',
            overflowY: 'auto',
          }}
        />
      </Sider>

      <Layout>
        {/* 顶部导航栏 */}
        <Header 
          style={{
            padding: '0 24px',
            background: token.colorBgContainer,
            borderBottom: `1px solid ${token.colorBorderSecondary}`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          {/* 左侧：折叠按钮 */}
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />

          {/* 右侧：用户信息和操作 */}
          <Space size="middle">
            {/* 通知铃铛 */}
            <Badge count={notifications?.length || 0} size="small">
              <Button 
                type="text" 
                icon={<BellOutlined />} 
                style={{ fontSize: '16px' }}
                onClick={() => navigate('/admin/notifications')}
              />
            </Badge>

            {/* 用户下拉菜单 */}
            <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
              <Space style={{ cursor: 'pointer' }}>
                <Avatar 
                  size="small" 
                  icon={<UserOutlined />} 
                  src={user?.avatar}
                />
                <Text>{user?.username || '管理员'}</Text>
              </Space>
            </Dropdown>
          </Space>
        </Header>

        {/* 主内容区域 */}
        <Content
          style={{
            margin: '16px 24px 0',
            minHeight: 'calc(100vh - 112px)',
          }}
        >
          {/* 面包屑导航 */}
          <Breadcrumb 
            items={generateBreadcrumb()}
            style={{ marginBottom: 16 }}
          />

          {/* 页面内容 */}
          <div
            style={{
              padding: 24,
              background: token.colorBgContainer,
              borderRadius: token.borderRadius,
              minHeight: 'calc(100vh - 180px)',
            }}
          >
            <Outlet />
          </div>
        </Content>

        {/* 底部信息栏 */}
        <Footer 
          style={{
            textAlign: 'center',
            background: token.colorBgContainer,
            borderTop: `1px solid ${token.colorBorderSecondary}`,
            padding: '12px 24px',
          }}
        >
          <Space split="|">
            <Text type="secondary">测试DEMO v1.0.0</Text>
            <Text type="secondary">在线用户: {user?.onlineUsers || 0}</Text>
            <Text type="secondary">© 2024 测试DEMO. All rights reserved.</Text>
          </Space>
        </Footer>
      </Layout>
    </Layout>
  );
};

export default AdminLayout;